/**
 * Created by fang.cai.liang@aliyun.com on 16/7/31.
 */

// 通过原型链的方式

//我们可发布的主题
var topics = {'J_S': "军事", "Z_Z": "政治", "J_J": "经济", "W_H": "文化"};

// 主题和订阅者的关系
var ts = {};

function Observer(userid) {
    this.userid = userid;
}

Observer.prototype = {

    publish: function (topic, contents) {
        if (topics[topic]) {
            // 1. 我们可能需要将 主题和内容存储起来

            // 2. 我们应该通知 所有订阅了该主题的订阅者
            setTimeout(function () {
                var subscriberList = ts[topic];
                if (!subscriberList) {
                    subscriberList = [];
                }
                for (var i = 0; i < subscriberList.length; i++) {
                    subscriberList[i].action(topic, contents);
                }
            }, 1000);

            return true;
        } else {
            // 发布的主题不合法
            return false;
        }
    },

    subscribe: function (userid, topic, func) {
        if (topics[topic]) {
            var subscriberList = ts[topic];
            if (!subscriberList) {
                subscriberList = [];
            }
            var subscriber = {"userid": userid, "action": func};
            subscriberList.push(subscriber);
            ts[topic] = subscriberList;
            return true;
        } else {
            return false;
        }
    },

    unsubscribe: function (userid, topic) {
        if (topics[topic]) {
            var subscriberList = ts[topic];
            if (subscriberList) {
                ts[topic] = subscriberList.filter(function (subscriber) {
                    if (userid != subscriber.userid) {
                        return subscriber;
                    }
                });
            }
        }
    }
};


var observer1 = new Observer(111);
observer1.subscribe(observer1.userid, "J_S", function(topic, contents){
    console.log(this.userid + " 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});
observer1.subscribe(observer1.userid, "Z_Z", function(topic, contents){
    console.log(this.userid + " 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});
observer1.subscribe(observer1.userid, "J_J", function(topic, contents){
    console.log(this.userid + " 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});

observer1.unsubscribe(observer1.userid, "J_J");

var observer2 = new Observer(222);
observer2.subscribe(observer2.userid, "J_J", function(topic, contents){
    console.error(this.userid + " 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});

var observer3 = new Observer(333);
observer3.subscribe(observer3.userid, "W_H", function(topic, contents){
    console.log(this.userid + " 收到发布的 " + topics[topic] + " 相关的内容: " + contents);
});


var observer4 = new Observer(444);
observer4.publish("J_S", "中国南海要开战了!!!!!!");
observer4.publish("J_J", "中国经济危机!!!!!!");
observer4.publish("Z_Z", "中国高层内斗习李不和!!!!!!");